﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Atom.Util;
using IdentityServer4;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace ApiServer.Controllers
{
 
    //[Authorize(AuthenticationSchemes = "Bearer")]
    //[Authorize]
    [Authorize(AuthenticationSchemes = IdentityServerConstants.LocalApi.AuthenticationScheme)]
    [ApiController]
    [Route("[controller]")]
    public class IdentityController : ControllerBase
    {

        [HttpGet("login")]
        public IActionResult Login()
        {
            var obj = new { a = "a" };
            return new JsonResult(obj);
        }

        [HttpGet("Get")]
        public IActionResult Get()
        {
            //foreach (var c in User.Claims)
            //{
            //    ObjectDumper.Write(c);
            //}
            var obj = from c in User.Claims select new { c.Type, c.Value };
            return new JsonResult(obj);
        }

        //[Authorize]
        [Authorize(AuthenticationSchemes = "Bearer")]
        [HttpGet(nameof(Index))]
        public string Index()
        {
            StringBuilder sb = new StringBuilder();

            string id_token = base.HttpContext.Request.Cookies["id_token"];
            var token_parts = id_token.Split('.');
            var header = Encoding.UTF8.GetString(Base64Url.Decode(token_parts[0]));
            var claims = Encoding.UTF8.GetString(Base64Url.Decode(token_parts[1]));
            var sign = Encoding.UTF8.GetString(Base64Url.Decode(token_parts[2]));

            sb.AppendLine($@"id_token;{id_token}");
            sb.AppendLine($@"header;{header}");
            sb.AppendLine($@"claims;{claims}");
            sb.AppendLine($@"sign;{sign}");
            sb.AppendLine("");


            foreach (var item in base.HttpContext.User.Identities.First().Claims)
            {

                sb.AppendLine($"{item.Type}:{item.Value}");
            }

            return sb.ToString();
        }

    }
}
